<template>
    <div class="content">
        <div class="content-left">
            <div class="form">
                <el-form :model="demandForm" :rules="demandRule" ref="demandForm" label-position="top"
                    class="demand-form">
                    <el-form-item label="需求标题" prop="service_title">
                        <el-input v-model="demandForm.service_title" placeholder="请填写需求标题"></el-input>
                    </el-form-item>
                    <el-form-item label="您想做的需求类型是" prop="service_cate">
                        <el-cascader v-model="demandForm.service_cate" class="select" :options="serviceCateList"
                            :props="props" clearable>
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="请填写需求描述" prop="describe">
                        <el-input :rows="5" type="textarea" v-model="demandForm.describe"
                            placeholder="请填写需求描述"></el-input>
                    </el-form-item>
                    <!-- <el-form-item>
                        <el-upload class="upload-demo" :action="fileUploadUrl" :on-preview="handlePreview"
                            :on-remove="handleRemove" :before-upload="beforeUpload" :before-remove="beforeRemove"
                            :on-success="successFile" multiple :limit="5" accept=".jpg,.jpeg,.png"
                            :on-exceed="handleExceed" :headers="header" :file-list="fileList">
                            <el-button class="upload-button" size="medium" style="border: none">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">
                                最多添加5张图片，每个图片大小不超过5MB
                            </div>
                        </el-upload>
                    </el-form-item> -->
                    <el-form-item prop="money">
                        <div slot="label">
                            <span style="padding-right: 50px;">
                                需求预算
                            </span>
                            <el-radio v-model="moneyType" label="1">一口价</el-radio>
                            <el-radio v-model="moneyType" label="2" @input="change_moneyType">范围报价</el-radio>
                        </div>
                        <div v-if="moneyType == '1'" style="display: flex;align-items: center;">
                            <span style="padding-right: 20px;">一口价</span>
                            <el-input class="fixed-input" v-model="demandForm.money" :placeholder="demandText"
                                :disabled="discussTrue">
                                <template slot="append">元</template>
                            </el-input>
                        </div>
                        <div v-if="moneyType == '2'" style="display: flex;align-items: center;">
                            <span style="padding-right: 20px;">范围报价</span>
                            <el-input-number v-model="moneyS" :controls="false" size="mini" :min="0" placeholder="最低预算"
                                style="width: 100px;"></el-input-number>
                            <span style="padding: 0 4px;">-</span>
                            <el-input-number v-model="moneyE" :controls="false" size="mini" :min="0" placeholder="最高预算"
                                style="width: 100px;"></el-input-number>
                        </div>
                        <div v-if="moneyType == '1'" class="money_tips">
                            <p style="font-size: 14px;">一口价说明：</p>
                            <p>1.当服务商觉得能完成任务且能接受您的任务酬金时，则可以报名参加接单,</p>
                            <p>2.之后您可在报名列表中选择雇佣您看中的服务商来完成您的任务。</p>
                        </div>
                        <div v-if="moneyType == '2'" class="money_tips">
                            <p style="font-size: 14px;">范围报价说明：</p>
                            <p>1.您可以选择一个预算范围，服务商可以在此范围内进行报价；</p>
                            <p>2.之后您可在报价列表中选择雇佣您觉得合适的服务商来完成您的任务。</p>
                        </div>
                    </el-form-item>
                    <el-form-item label="投标截止" prop="end_time">
                        <el-date-picker class="fixed-input" v-model="demandForm.end_time" type="date"
                            format="yyyy-MM-dd" value-format="yyyy-MM-dd 23:59:59" :picker-options="pickerOptions"
                            placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="服务地址" prop="address">
                        <!-- <el-cascader
                            ref="cascaderAddr"
                            class="fixed-input"
                            v-model="demandForm.address"
                            :options="region"
                            :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                            }"
                            @change="changeAddr"
                            clearable
                        ></el-cascader> -->
                        <el-cascader ref="cascaderAddr" class="fixed-input" v-model="demandForm.address"
                            :options="region" :props="{
                                value: 'id',
                                label: 'name',
                                children: 'children',
                            }" clearable filterable @change="changeAddr"></el-cascader>
                    </el-form-item>
                </el-form>
            </div>
            <div class="line-bottom"></div>
            <div class="check-box">
                <el-checkbox v-model="demandChecked"></el-checkbox>
                <div class="check-text">
                    阅读并同意 《<span style="font-size: 14px; color: #3785d4; cursor: pointer"
                        @click="goRoute('2')">小竹企服内容管理规则</span>》
                </div>
            </div>
            <div class="demand-button">
                <el-button :loading="submitLoading" class="submit" @click="submit('demandForm')">
                    发布任务
                </el-button>
            </div>
        </div>
        <div class="content-right">
            <div class="right-title">
                <span>人工协助发布</span>
            </div>
            <div class="right-phone">
                <img src="~/assets/images/service/yb-img/telephone.png" alt="" />
                <div class="phone-text">
                    <span style="font-size: 16px; color: #060621">
                        小竹客服电话
                    </span>
                    <span style="font-size: 18px; color: #1B8DFF">
                        15205695320
                    </span>
                </div>
            </div>
            <div class="phone-button">
                <el-button class="phone" @click="goKefu"> 联系客服 </el-button>
            </div>
            <div class="right-tags">
                <div class="tags">
                    <img src="~/assets/images/service/xzwm1.png" alt="" />
                    <div class="tags-text">
                        <span style="font-weight: 500"> 服务专业 </span>
                        <span style="font-size: 12px; color: #9e9e9e">
                            服务商实名认证，精准入驻平台
                        </span>
                    </div>
                </div>
                <div class="tags">
                    <img src="~/assets/images/service/xzwm2.png" alt="" />
                    <div class="tags-text">
                        <span style="font-weight: 500"> 价格透明 </span>
                        <span style="font-size: 12px; color: #9e9e9e">
                            收费依规依据，资金全面监管
                        </span>
                    </div>
                </div>
                <div class="tags">
                    <img src="~/assets/images/service/xzwm3.png" alt="" />
                    <div class="tags-text">
                        <span style="font-weight: 500"> 流程可靠 </span>
                        <span style="font-size: 12px; color: #9e9e9e">
                            服务进度实时可视，流程标准可控
                        </span>
                    </div>
                </div>
                <div class="tags">
                    <img src="~/assets/images/service/xzwm4.png" alt="" />
                    <div class="tags-text">
                        <span style="font-weight: 500"> 口碑真实 </span>
                        <span style="font-size: 12px; color: #9e9e9e">
                            服务评价真实有效，可参考可信赖
                        </span>
                    </div>
                </div>
            </div>
            <div class="wx-official-account">
                <img src="~/assets/images/index/wx_code.png" alt="" />
                关注公众号 <br />
                时刻获取消息通知
            </div>
        </div>

        <el-dialog title="确认支付" :visible.sync="payCodeShow" width="400px" center>
            <div class="pay_code">
                <vue-qr style="display: block;margin: 0 auto;" ref="qrCode" :text="payCode" color-dark="black"
                    :margin="0" width="240px" height="240px"></vue-qr>
                <div class="pay_text">任务发布请支付<span>{{ pay_money }}元</span></div>
                <div class="go_vip" @click="set_payVipShow({ show: true, index: 1 }); payCodeShow = false">
                    加入小竹会员可享不限次数查询
                    ></div>
                <div class="xieyi">
                    小竹企服服务协议
                    <img src="~/assets/images/service/biao.png" alt="">
                </div>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { getAllCate, addTask, pc_user_release_demand, get_demand_id } from "@/assets/api/service";
import axios from "axios";
import region from "@/assets/json/region-just-city.json";
import { mapActions, mapMutations, mapState } from "vuex";
import { goTopSmooth } from "@/assets/utils/utils";

export default {
    components: {},
    head() {
        return {
            title: "发布需求-【小竹财税平台】",
            meta: [
                {
                    hid: "keywords",
                    name: "keywords",
                    content: "小竹财税,服务商,小竹企服",
                },
            ],
        };
    },
    layout: "serverHome",
    data() {
        return {
            payCodeShow: false,
            // https://h5.xzcs2022.com/juhe-pay/?combo_id=646&token=a94cd3da-2ce4-4c6e-a7d9-5ad786379920&money=1&type=6&order_sn=202506111636525447
            payCode: '',
            pay_money: 0,
            moneyType: '1',
            moneyS: '',
            moneyE: '',

            submitLoading: false, //提交按钮加载中
            demandForm: {
                service_title: '',
                service_cate: [],
                money: "",
                end_time: "",
                describe: "",
                address: [],
            },
            serviceCateList: [],
            demandRule: {
                service_title: [
                    {
                        required: true,
                        message: "请填写具体需求标题",
                        trigger: "blur",
                    },
                ],
                service_cate: [
                    {
                        required: true,
                        message: "请选择服务项目",
                        trigger: "change",
                    },
                ],
                describe: [
                    {
                        required: true,
                        message: "请填写具体需求描述",
                        trigger: "blur",
                    },
                ],
                end_time: [
                    {
                        required: true,
                        message: "请选择投标截止日期",
                        trigger: "change",
                    },
                ],
                address: [
                    {
                        required: true,
                        message: "请选择服务地址",
                        trigger: "change",
                    },
                ],
            },
            fileList: [],
            fileUploadUrl: "",
            region: [],
            token: "",
            demandChecked: false,
            props: {
                label: "name",
                value: "id",
                children: "child",
            },
            cityName: "", //服务地址的城市名

            //面议切换
            discussTrue: false,
            demandText: "请输入需求预算",
            pickerOptions: {
                disabledDate(date) {
                    return date.getTime() < new Date().getTime() + 86400000 * 14;
                },
            },
        };
    },
    created() { },
    beforeMount() {
        this.$options.components["vue-qr"] = () => import("vue-qr");
    },
    mounted() {
        this.init();
        this.token = localStorage.getItem("token");
        if (this.token) {
            this.getUserInfo();
        } else {
            this.$alert("请登录", "请登录后查看", {
                confirmButtonText: "确定",
                callback: (action) => {
                    if (action == 'confirm')
                        this.$router.push({ path: "/" });
                },
            });
        }
        goTopSmooth();
    },
    computed: {
        ...mapState("common", {
            userInfo: (state) => state.userInfo,
        }),
        header() {
            return {
                token: this.userInfo && this.token ? this.token : "",
            };
        },
    },
    methods: {
        ...mapMutations("common", ["set_payVipShow", "setuserInfo"]),
        ...mapActions("common", ["getUserInfo"]),

        //初始化
        init() {
            this.fileUploadUrl = axios.defaults.baseURL + "/api/common/upload";
            this.getCate();
            let regionList = region;
            for (let items of regionList) {
                for (let item of items.children) {
                    delete item.children;
                }
            }
            this.region = regionList;

            // 创建一个新的Date对象，表示当前时间
            let currentDate = new Date();
            // 设置时间为三天后的时间
            currentDate.setDate(currentDate.getDate() + 15);
            // 格式化日期，这里我们假设你想要 "YYYY-MM-DD" 的格式
            let year = currentDate.getFullYear();
            let month = String(currentDate.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并使用padStart填充前导0
            let day = String(currentDate.getDate()).padStart(2, "0"); // 使用padStart填充前导0

            this.demandForm.end_time = `${year}-${month}-${day} 23:59:59`;
        },

        //获取全部服务类目
        async getCate() {
            const res = await getAllCate({});
            if (res.code == 1) {
                for (let items of res.data) {
                    for (let item of items.child) delete item.child;
                }
                this.serviceCateList = res.data;
            }
        },

        //切换自定义价格
        changeDiscuss() {
            this.discussTrue = !this.discussTrue;
            if (this.discussTrue) {
                this.demandText = "面议";
                this.demandForm.money = "面议";
            } else {
                this.demandText = "请输入需求预算";
                this.demandForm.money = "";
            }
        },

        //文件上传删除的钩子
        handleRemove(file, fileList) {
            console.log(file, fileList, "删除之后的回调");
            this.fileList.forEach((item, index) => {
                if (file.response.data.fullurl === item) {
                    this.fileList.splice(index, 1);
                }
            });
        },
        handlePreview(file) {
            console.log(file, "这里会有参数吗");
        },
        handleExceed(files, fileList) {
            this.$message.warning("文件上传数量不超过5个");
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        beforeUpload(file) {
            const isType =
                file.type == "image/jpeg" ||
                file.type == "image/jpg" ||
                file.type == "image/png";
            const isLtMB = file.size / 1024 / 1024 < 5;

            if (!isType) {
                this.$message.error("上传图片只能是 JPG,JPEG,PNG 格式!");
            }
            if (!isLtMB) {
                this.$message.error("上传图片大小不能超过 5MB!");
            }
            return isType && isLtMB;
        },
        successFile(res, file, fileList) {
            console.log(res, "上传成功后的回调");
            this.fileList.push(res.data.fullurl);
        },

        //服务地址的选择
        changeAddr(citys) {
            // this.cityName =
            //     this.$refs["cascaderAddr"].getCheckedNodes()[0].label;
            // console.log(
            //     this.$refs["cascaderAddr"].getCheckedNodes()[0].pathLabels
            // );

            let label = "";
            for (let items of this.region) {
                if (items.id == citys[0]) {
                    for (let item of items.children) {
                        if (item.id == citys[1]) {
                            label = item.name;
                        }
                    }
                }
            }
            this.cityName = label;
        },

        //提交校验
        submit(formName) {
            if (this.submitLoading) return;
            this.submitLoading = true;

            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.addDemand();
                } else {
                    console.log("error submit!!");
                    this.submitLoading = false;

                    return false;
                }
            });
        },

        //
        change_moneyType() {
            if (!this.moneyE) this.moneyE = undefined
            if (!this.moneyS) this.moneyS = undefined
        },

        //发布任务需求
        async addDemand() {
            if (this.demandChecked == false) {
                this.$message.warning("请阅读并同意小竹企服任务发布协议");
                this.submitLoading = false;
                return;
            }

            const time =
                this.$moment(this.demandForm.end_time).valueOf() / 1000;

            let obj = {
                name: this.demandForm.service_title,
                one_cate_id: this.demandForm.service_cate[0],
                two_cate_id: this.demandForm.service_cate[1],
                third_cate_id: this.demandForm.service_cate[2],
                describe: this.demandForm.describe,
                end_time: time,
                city_code: Number(this.demandForm.address[1]),
                city_name: this.cityName,
                annex: this.fileList.join(","),
                money_type: this.moneyType
            };
            if (this.moneyType == '1') {
                if (this.demandForm.money == 0) {
                    this.$message.warning("预算不得等于0");
                    this.submitLoading = false;
                    return;
                }
                obj.money = this.demandForm.money
            } else {
                if (!this.moneyE) {
                    this.$message.warning("请填写价格范围");
                    this.submitLoading = false;
                    return;
                }
                if (this.moneyS > this.moneyE) {
                    this.$message.warning("请正确填写价格范围");
                    this.submitLoading = false;
                    return;
                }
                obj.money = this.moneyS + '-' + this.moneyE
            }
            const res = await addTask(obj);
            if (res.code == 1) {
                // this.$message.success("任务发布成功");
                // this.$refs["demandForm"].resetFields();
                this.submitLoading = false;
                // this.$router.push({
                //     path: "/service/demandlist",
                // });
                // 获取付款二维码
                if (res.data.pay_money != '0') {
                    this.pc_user_release_demand(res.data)
                    this.pay_money = res.data.pay_money
                } else {
                    const res2 = await pc_user_release_demand({
                        money: res.data.pay_money,
                        combo_id: res.data.id,
                        order_sn: res.data.order_sn
                    })
                    this.$router.push({
                        path: "/service/demanddetail?id=" + res.data.id,
                    });
                }
            } else {
                this.submitLoading = false;
            }
        },

        async pc_user_release_demand(data) {
            const res = await pc_user_release_demand({
                money: data.pay_money,
                combo_id: data.id,
                order_sn: data.order_sn
            })
            if (res.code == 1) {
                this.payCode = res.data
                this.payCodeShow = true;
                // 轮询开始
                setTimeout(() => {
                    this.get_demand_id(data.id)
                }, 1500)
            }
        },

        async get_demand_id(id) {
            if (!this.payCodeShow) return
            const res = await get_demand_id({
                demand_id: id
            })
            if (res.code == 1 && res.data.info.pay_time) {
                this.payCodeShow = false
                this.$alert('发布成功', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                        if (action == 'confirm')
                            this.$router.push({
                                path: "/service/demanddetail?id=" + id,
                            });
                    }
                });

            } else {
                setTimeout(() => {
                    this.get_demand_id(id)
                }, 1500)
            }

        },

        //跳转客服
        goKefu() {
            let { href } = this.$router.resolve({
                path: "/chatlink",
            });
            window.open(href, "_blank");
        },

        //跳转发布任务规则
        goRoute(val) {
            let newRoute = this.$router.resolve({
                path: "/ServiceAgreement",
                query: {
                    index: val,
                },
            });
            window.open(newRoute.href, "_blank");
        },
    },
};
</script>

<style lang="scss" scoped>
.content {
    width: 1200px;
    margin: 20px auto 60px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    position: relative;

    .content-left {
        width: 945px;
        background: #fff;
        border-radius: 4px;

        .form {
            margin-top: 50px;
            padding: 0 60px;

            .select {
                width: 100%;
            }

            .textarea {
                min-height: 260px;
            }

            .upload-button {
                background: #1B8DFF;
                color: #fff;
            }

            .fixed-input {
                width: 260px;

                .el-input__inner {
                    cursor: pointer;
                }
            }

            .money_tips {
                font-weight: 400;
                font-size: 12px;
                color: #060621;
                line-height: 24px;
                background: #F7F8FA;
                border-radius: 10px;
                padding: 13px 20px;
                margin-top: 12px;
            }
        }

        .line-bottom {
            margin-top: 45px;
            width: 100%;
            height: 1px;
            background: #eaeaea;
        }

        .check-box {
            margin-top: 42px;
            padding: 0 60px;
            display: flex;
            align-items: center;

            .check-text {
                margin-left: 10px;
                font-size: 14px;
                color: #999;
            }
        }

        .demand-button {
            margin-top: 30px;
            padding: 0 60px;

            .submit {
                width: 250px;
                height: 60px;
                background: #1B8DFF;
                color: #fff;
                border: none;
            }

            margin-bottom: 116px;
        }
    }

    .content-right {
        width: 275px;
        background: #fff;
        margin-left: 20px;
        border-radius: 4px;

        .right-title {
            width: 100%;
            height: 80px;
            border-bottom: solid 1px #eeeeee;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #333;
            font-weight: 500;
            font-family: Source Han Sans CN-Medium, Source Han Sans CN;
        }

        .right-phone {
            margin-top: 42px;
            padding: 0 20px;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
                width: 56px;
                height: 42px;
            }

            .phone-text {
                margin-left: 8px;
                display: flex;
                flex-direction: column;
            }
        }

        .phone-button {
            margin-top: 32px;
            padding: 0 20px;

            .phone {
                height: 48px;
                width: 235px;
                background: rgba($color: #1B8DFF, $alpha: 0.1);
                border-radius: 4px;
                color: #1B8DFF;
                border: 1px solid #1B8DFF;
            }
        }

        .right-tags {
            margin-bottom: 50px;
            padding: 0 20px;

            .tags {
                margin-top: 46px;
                display: flex;
                align-items: center;
                justify-content: space-between;

                img {
                    width: 40px;
                    height: 40px;
                }

                .tags-text {
                    margin-left: 10px;
                    flex: 1;
                    display: flex;
                    flex-direction: column;
                }
            }
        }
    }
}

.pay_code {
    .pay_text {
        font-weight: 400;
        font-size: 24px;
        color: #060621;
        padding-top: 17px;
        text-align: center;

        span {
            color: #FA5151;
        }
    }

    .go_vip {
        width: 343px;
        height: 49px;
        line-height: 49px;
        text-align: center;
        background: rgba(27, 141, 255, 0.1);
        border-radius: 5px;
        border: 1px solid #1B8DFF;
        font-weight: 400;
        font-size: 18px;
        color: #1B8DFF;
        margin: 26px auto 0;
        cursor: pointer;

        &:hover {
            opacity: 0.8;
        }
    }

    .xieyi {
        font-weight: 400;
        font-size: 18px;
        color: #060621;
        padding-top: 13px;
        line-height: 26px;
        text-align: center;
        cursor: pointer;

        &:hover {
            text-decoration: underline;
        }

        img {
            position: relative;
            width: 10px;
            height: 10px;
            top: -5px;
        }
    }
}

.wx-official-account {
    text-align: center;
    font-size: 14px;
    font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
    font-weight: 400;
    color: #333333;
    line-height: 24px;
    padding-bottom: 30px;

    img {
        width: 152px;
        height: 152px;
        margin: 0 auto;
        display: block;
    }
}
</style>./postdemand.vue